<!--
 * @Description: 角色选择用户
 * @Author: DHL
 * @Date: 2022-04-08 09:04:53
 * @LastEditors: DHL
 * @LastEditTime: 2022-10-11 15:10:04
-->
<template>
  <tw-dialog
    v-model="visible"
    :title="title"
    :loading="loading"
    :showZoom="false"
    width="1100px"
    height="600px"
    heightContent="580px"
    customClass="role-select-user-wrapper"
    @close="handleClose"
  >
    <tw-layout @refresh="handleRefresh" @search="handleSearch" @reset="handleReset">
      <!-- 按钮组 -->
      <template #btns>
        <el-button class="item" type="primary" @click="handleRefresh">
          <svg-icon iconClass="sync"></svg-icon>
          刷新
        </el-button>
        <el-button class="item" type="warning" @click="handleSearch">
          <svg-icon iconClass="search"></svg-icon>
          查询
        </el-button>
        <el-button class="item" type="info" @click="handleReset">
          <svg-icon iconClass="reload"></svg-icon>
          重置
        </el-button>

        <el-divider class="item"></el-divider>

        <el-button class="item" type="primary" @click="handleSubmit()">
          <svg-icon iconClass="plus"></svg-icon>
          确认选择
        </el-button>
      </template>

      <!-- 查询表单 -->
      <template #header>
        <el-form ref="searchFormRef" :model="searchForm" label-width="90px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="机构">
                <el-cascader
                  v-model="searchForm.orgId"
                  :options="orgTreeData"
                  :props="{ checkStrictly: true, value: 'id', label: 'name', children: 'children' }"
                  filterable
                  clearable
                  placeholder="请选择机构"
                />
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="登陆名称">
                <el-input
                  v-model="searchForm.loginName"
                  clearable
                  placeholder="请输入登陆名称"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="姓名">
                <el-input v-model="searchForm.name" clearable placeholder="请输入姓名"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="用户类型">
                <el-select v-model="searchForm.userType" clearable placeholder="请选择用户类型">
                  <tw-dic dicKey="USERTYPE"></tw-dic>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="用户状态">
                <el-select v-model="searchForm.status" clearable placeholder="请选择用户状态">
                  <tw-dic dicKey="USER_STATUS"></tw-dic>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="手机号码">
                <el-input
                  v-model="searchForm.phone"
                  clearable
                  placeholder="请输入手机号码"
                ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="职务">
                <el-input
                  v-model="searchForm.position"
                  clearable
                  placeholder="请输入职务"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>

      <!-- 数据表格 -->
      <tw-table
        ref="tableRef"
        :loading="loading"
        :options="tableOptions"
        :events="tableEvents"
        :data="tableData"
        @search="searchList"
      >
      </tw-table>
    </tw-layout>
  </tw-dialog>
</template>

<script setup lang="ts">
  import { computed, reactive, ref } from 'vue'
  import { assign, cloneDeep } from 'lodash-es'
  import { TwTableOptions } from '/@/types/table.d'
  import { UserModel, UserPageParams } from '/@/api/system/model/userModel'
  import { apiSearchRoleSelectUsers } from '/@/api/system/user'
  import { RoleModel } from '/@/api/system/model/roleModel'
  import { apiRoleSaveRoleUsers } from '/@/api/system/role'
  import { ElMessage } from 'element-plus'
  import { arrayLastValue, arraySerializeToStr, listToTree } from '/@/utils/twUtils'
  import { apiOrganizationSearchTree } from '/@/api/system/organization'

  const emit = defineEmits(['search'])

  //////////////////////////////////////////////////
  // 属性
  //////////////////////////////////////////////////

  /**
   * 显示弹框
   */
  const visible = ref(false)

  const loading = ref(false)

  /**
   * 标题
   */
  const title = computed(() => {
    let num = 0
    let selectRows: Array<UserModel> = []
    if (tableRef.value) {
      selectRows = tableRef.value.getSelectRows(true)
      num = selectRows.length
    }

    return `【角色：${role.name}】【已选择用户数：${num}】`
  })

  /**
   * 表格数据
   */
  const tableData = ref()

  /**
   * 查询表单
   */
  const searchFormRef = ref()

  /**
   * 数据列表
   */
  const tableRef = ref()

  /**
   * 角色
   */
  const role = reactive({
    id: '',
    name: '',
    orgId: '',
    orgName: ''
  })

  //////////////////////////////////////////////////
  // 查询表单
  //////////////////////////////////////////////////

  const defaultSearchForm = {
    orgId: '',
    loginName: '', // 登陆名称
    name: '', // 姓名
    userType: '', // 用户类型
    phone: '', // 手机号码
    mail: '', // 邮箱
    status: '1', // 用户状态（0，失效；1，生效）
    position: '' // 职务
  }

  /**
   * 查询表单
   */
  const searchForm = reactive(cloneDeep(defaultSearchForm))

  //////////////////////////////////////////////////
  // 表格
  //////////////////////////////////////////////////

  /**
   * 表格配置
   */
  const tableOptions = reactive<TwTableOptions>({
    id: 'roleUserListTable',
    checkboxConfig: {
      reserve: true,
      trigger: 'row'
    },
    sortConfig: {
      defaultSort: [{ field: 'loginName', order: 'asc' }]
    },
    columns: [
      { type: 'checkbox', fixed: 'left', title: '', width: 40 },
      { type: 'seq', fixed: 'left', title: '序号', width: 50 },
      { field: 'loginName', title: '登陆名称', sortable: true, width: 110 },
      { field: 'name', title: '姓名', sortable: true, width: 110 },
      {
        field: 'status',
        title: '用户状态',
        sortable: true,
        width: 110,
        params: { dict: 'USER_STATUS' }
      },
      { field: 'userType', title: '用户类型', sortable: true, params: { dict: 'USERTYPE' } },
      { field: 'position', title: '职务', sortable: true },
      { field: 'phone', title: '手机号码' },
      { field: 'mail', title: '邮箱' }
    ]
  })

  /**
   * 绑定事件
   */
  const tableEvents = reactive({})

  //////////////////////////////////////////////////
  // 函数
  //////////////////////////////////////////////////

  /**
   * 查询表格数据函数
   * @param queryParams
   */
  function searchList(queryParams: UserPageParams) {
    loading.value = true

    let orgId = ''
    if (searchForm.orgId && searchForm.orgId.length > 0) {
      orgId = arrayLastValue(searchForm.orgId)
    }

    apiSearchRoleSelectUsers(
      assign(queryParams, searchForm, {
        roleId: role.id,
        orgId: orgId
      })
    )
      .then((result) => {
        tableData.value = result
      })
      .catch(() => {})
      .finally(() => {
        loading.value = false
      })
  }

  /**
   * 查询表格数据
   */
  function handleSearch() {
    tableRef.value.handleQuery()
  }

  /**
   * 刷新
   */
  function handleRefresh() {
    tableRef.value.handleReload()
  }

  /**
   * 重置
   */
  function handleReset() {
    assign(searchForm, cloneDeep(defaultSearchForm))
    tableRef.value.handleQuery()
  }

  /**
   * 显示弹框
   */
  function handleOpen(params: RoleModel) {
    visible.value = true
    assign(role, params)

    handleSearchOrgTree()
  }

  /**
   * 关闭弹框
   */
  function handleClose() {
    visible.value = false
  }

  /**
   * 提交当前选中行数据
   */
  function handleSubmit() {
    const selectRows: Array<UserModel> = tableRef.value.getSelectRows(true)
    if (selectRows.length < 1) {
      ElMessage.warning('请选择用户')
      return
    }
    loading.value = true
    const userIds = arraySerializeToStr(selectRows, 'id')
    apiRoleSaveRoleUsers({ roleId: role.id, userIds: userIds })
      .then((result) => {
        if (result?.success) {
          ElMessage.success(result.message)
          emit('search')
          handleClose()
        } else {
          ElMessage.error(result?.message)
        }
      })
      .finally(() => {
        loading.value = false
      })
  }

  //////////////////////////////////////////////////
  // 机构
  //////////////////////////////////////////////////
  const orgTreeData = ref()

  /**
   * 查询机构数据
   */
  function handleSearchOrgTree() {
    apiOrganizationSearchTree().then((result) => {
      if (result?.success) {
        orgTreeData.value = listToTree(result?.data ? result.data : [], 'id', 'parentOrgId', '')
      }
    })
  }

  defineExpose({ handleOpen })
</script>

<style lang="scss"></style>
